<template>
  <div class="page-container">
    <h1 class="metro-title"><i class="metro-icon"></i>缓冲区分析</h1>
    <div id="mapView" class="map-view">
      <!-- 图层控制面板 -->
      <div class="layer-control-panel">
        <el-card class="layer-card">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="图层显示控制" name="layers">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-checkbox
                  v-model="layerVisibility.subwayLine"
                  @change="toggleLayerVisibility('subwayLine')"
                  class="metro-checkbox"
                  >地铁线路</el-checkbox
                >
                <el-checkbox
                  v-model="layerVisibility.subwayStation"
                  @change="toggleLayerVisibility('subwayStation')"
                  class="metro-checkbox"
                  >地铁站点</el-checkbox
                >
                <el-checkbox
                  v-model="layerVisibility.restaurant"
                  @change="toggleLayerVisibility('restaurant')"
                  class="metro-checkbox"
                  >餐饮设施</el-checkbox
                >
                <el-checkbox
                  v-model="layerVisibility.community"
                  @change="toggleLayerVisibility('community')"
                  class="metro-checkbox"
                  >小区</el-checkbox
                >
              </el-space>
            </el-collapse-item>
            <el-collapse-item title="站点搜索" name="stationSearch">
              <el-space direction="vertical" alignment="stretch" size="small">
                <el-input
                  v-model="stationSearchText"
                  placeholder="输入站点名称"
                  clearable
                  class="metro-input"
                >
                  <template #append>
                    <el-button @click="searchStation">
                      <el-icon><Search /></el-icon>
                    </el-button>
                  </template>
                </el-input>
              </el-space>
            </el-collapse-item>
            <el-collapse-item title="缓冲区分析" name="bufferAnalysis">
              <el-space direction="vertical" alignment="stretch" size="small">
                <div class="buffer-analysis-tip">选择站点后可进行缓冲区分析</div>
                <div class="search-radius-slider">
                  <span>缓冲区半径: {{ bufferRadius }}米</span>
                  <el-slider v-model="bufferRadius" :min="100" :max="5000" :step="500"></el-slider>
                </div>
                <el-checkbox-group v-model="selectedFacilityTypes" class="facility-checkbox-group">
                  <el-checkbox label="restaurant" class="metro-checkbox">餐饮设施</el-checkbox>
                  <el-checkbox label="community" class="metro-checkbox">小区</el-checkbox>
                </el-checkbox-group>
                <el-button
                  type="primary"
                  @click="performBufferAnalysis"
                  :disabled="!hasSelectedStation"
                  class="buffer-analysis-btn"
                >
                  <el-icon><DataAnalysis /></el-icon> 执行缓冲区分析
                </el-button>
              </el-space>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>

      <!-- 搜索结果对话框 -->
      <el-dialog
        v-model="searchResultVisible"
        title="站点搜索结果"
        width="400px"
        :key="refreshStationKey"
        destroy-on-close
      >
        <el-table
          :data="searchResults"
          height="300"
          style="width: 100%"
          @row-click="handleStationRowClick"
          highlight-current-row
        >
          <el-table-column prop="attributes.StationName" label="站点名称" />
          <el-table-column prop="attributes.TransferLines" label="所属线路" />
        </el-table>
      </el-dialog>

      <!-- 站点信息对话框 -->
      <el-dialog
        v-model="stationInfoVisible"
        title="站点详情"
        width="400px"
        :key="stationRefreshKey"
        destroy-on-close
      >
        <template v-if="selectedStation">
          <div class="station-info">
            <p><strong>站点名称:</strong> {{ selectedStation.attributes.StationName }}</p>
            <p><strong>所属线路:</strong> {{ selectedStation.attributes.TransferLines }}</p>
            <p><strong>站点类型:</strong> {{ selectedStation.attributes.StationType }}</p>
          </div>
        </template>
      </el-dialog>

      <!-- 分析结果对话框 -->
      <el-dialog
        v-model="analysisResultVisible"
        title="缓冲区分析结果"
        width="600px"
        destroy-on-close
      >
        <el-tabs v-model="activeResultTab">
          <el-tab-pane label="餐饮设施" name="restaurant" v-if="restaurantResultsCount > 0">
            <el-table :data="restaurantResults" height="300" style="width: 100%">
              <el-table-column prop="attributes.名称" label="名称" />
              <el-table-column prop="attributes.地址" label="地址" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="zoomToFeature(scope.row)">
                    定位
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="小区" name="community" v-if="communityResultsCount > 0">
            <el-table :data="communityResults" height="300" style="width: 100%">
              <el-table-column prop="attributes.name" label="名称" />
              <el-table-column prop="attributes.address" label="地址" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button type="primary" size="small" @click="zoomToFeature(scope.row)">
                    定位
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="统计信息" name="statistics">
            <div class="statistics-info">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-statistic title="餐饮设施数量" :value="restaurantResultsCount">
                    <template #suffix>
                      <el-icon><Food /></el-icon>
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="12">
                  <el-statistic title="小区数量" :value="communityResultsCount">
                    <template #suffix>
                      <el-icon><House /></el-icon>
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
              <el-divider content-position="center">设施类型分布</el-divider>
              <div ref="facilityDistributionChartRef" class="chart-container" style="height: 300px; width: 100%;"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, DataAnalysis, Food, House, PieChart } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import Query from '@arcgis/core/rest/support/Query.js'
import Circle from '@arcgis/core/geometry/Circle.js'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import SimpleFillSymbol from '@arcgis/core/symbols/SimpleFillSymbol.js'
import Polygon from '@arcgis/core/geometry/Polygon.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import subway from '@/assets/subway.png'

// 地图和图层变量
let view: MapView | null = null
let subwayLineLayer: FeatureLayer | null = null
let subwayStationLayer: FeatureLayer | null = null
let restaurantLayer: FeatureLayer | null = null
let communityLayer: FeatureLayer | null = null
let bufferGraphicsLayer: GraphicsLayer | null = null
let highlightGraphicsLayer: GraphicsLayer | null = null

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'stationSearch', 'bufferAnalysis'])
const refreshStationKey = ref(0)

// 图层可见性控制
const layerVisibility = ref({
  subwayLine: true,
  subwayStation: true,
  restaurant: false,
  community: false,
})

// 查询相关
const stationSearchText = ref('')
// 使用普通变量存储ArcGIS对象
let searchResultsRaw: Graphic[] = []
// 添加响应式变量存储简化后的结果
const searchResults = ref<{id: number, attributes: any, objectId: number, type: string}[]>([])
// 添加响应式变量存储结果数量
const searchResultsCount = ref(0)

// 对话框显示控制
const searchResultVisible = ref(false)
const stationInfoVisible = ref(false)
const analysisResultVisible = ref(false)

// 站点选择状态
const hasSelectedStation = ref(false)
let selectedStation: Graphic | null = null
const stationRefreshKey = ref(0)

// 缓冲区分析相关
const bufferRadius = ref(500)
const selectedFacilityTypes = ref(['restaurant', 'community'])
// 使用普通变量存储ArcGIS对象
let restaurantResultsRaw: Graphic[] = []
let communityResultsRaw: Graphic[] = []
// 添加响应式变量存储简化后的结果，用于在模板中显示
const restaurantResults = ref<{id: number, attributes: any, objectId: number, type: string}[]>([])
const communityResults = ref<{id: number, attributes: any, objectId: number, type: string}[]>([])
// 添加响应式变量存储结果数量
const restaurantResultsCount = ref(0)
const communityResultsCount = ref(0)
const activeResultTab = ref('restaurant')

// 图表相关
const facilityDistributionChartRef = ref<HTMLElement | null>(null)
let facilityDistributionChart: echarts.ECharts | null = null

// 切换图层可见性
const toggleLayerVisibility = (layerName: string) => {
  if (layerName === 'subwayLine' && subwayLineLayer) {
    subwayLineLayer.visible = layerVisibility.value.subwayLine
  } else if (layerName === 'subwayStation' && subwayStationLayer) {
    subwayStationLayer.visible = layerVisibility.value.subwayStation
  } else if (layerName === 'restaurant' && restaurantLayer) {
    restaurantLayer.visible = layerVisibility.value.restaurant
  } else if (layerName === 'community' && communityLayer) {
    communityLayer.visible = layerVisibility.value.community
  }
}

// 搜索站点
const searchStation = () => {
  if (!stationSearchText.value.trim()) {
    ElMessage.warning('请输入站点名称')
    return
  }

  if (!subwayStationLayer) {
    ElMessage.error('地铁站点图层未加载')
    return
  }

  // 创建查询对象
  const query = new Query()
  query.where = `StationName LIKE '%${stationSearchText.value}%'`
  query.outFields = ['*']
  query.returnGeometry = true

  // 执行查询
  subwayStationLayer
    .queryFeatures(query)
    .then((results) => {
      nextTick(() => {
        refreshStationKey.value++
      })
      if (results.features && results.features.length > 0) {
        // 存储原始ArcGIS对象
        searchResultsRaw = results.features
        // 提取需要的属性到简单对象中
        searchResults.value = results.features.map((feature, index) => ({
          id: index,
          attributes: feature.attributes,
          // 存储ObjectID而不是几何对象
          objectId: feature.attributes.OBJECTID || feature.attributes.objectid || index,
          // 添加类型标识
          type: 'station'
        }))
        searchResultsCount.value = searchResultsRaw.length
        console.log('查询结果数量:', searchResultsRaw.length)
        searchResultVisible.value = true
      } else {
        searchResultsRaw = []
        searchResults.value = []
        searchResultsCount.value = 0
        searchResultVisible.value = true
        ElMessage.info('未找到匹配的站点')
      }
    })
    .catch((error) => {
      console.error('查询站点出错:', error)
      ElMessage.error('查询站点失败')
    })
}

// 处理搜索结果行点击
const handleStationRowClick = (row: {id: number, attributes: any, objectId: number, type: string}) => {
  // 根据id找到原始的ArcGIS对象
  const originalFeature = searchResultsRaw[row.id]
  if (!originalFeature) {
    console.error('找不到对应的原始要素')
    return
  }

  // 存储原始ArcGIS对象用于后续分析
  selectedStation = originalFeature
  hasSelectedStation.value = true
  searchResultVisible.value = false
  stationInfoVisible.value = true

  // 如果有地图视图，则定位到该站点
  if (view && originalFeature.geometry) {
    view.goTo({
      target: originalFeature.geometry,
      zoom: 15,
    })
  }
}

// 执行缓冲区分析
const performBufferAnalysis = async () => {
  if (!selectedStation || !view) {
    ElMessage.warning('请先选择一个地铁站点')
    return
  }

  try {
    // 清除之前的缓冲区和高亮图形
    if (bufferGraphicsLayer) {
      bufferGraphicsLayer.removeAll()
    }
    if (highlightGraphicsLayer) {
      highlightGraphicsLayer.removeAll()
    }

    // 创建缓冲区
    // 确保geometry不为空
    if (!selectedStation.geometry) {
      throw new Error('站点几何对象为空')
    }

    // 使用try-catch块来捕获可能的错误
    let bufferGeometry
    try {
      // 打印站点几何对象信息，用于调试
      console.log('站点几何对象类型:', selectedStation.geometry.type)
      console.log('站点几何对象空间参考:', selectedStation.geometry.spatialReference)

      // 确保几何对象有效
      if (!selectedStation.geometry.spatialReference) {
        throw new Error('几何对象缺少空间参考')
      }

      // 使用Circle类创建缓冲区
      // 检查几何对象类型
      if (selectedStation.geometry.type === 'point') {
        // 对于点几何对象，使用Circle类创建圆形缓冲区
        // Circle类本身就是一个多边形
        bufferGeometry = new Circle({
          center: selectedStation.geometry,
          radius: bufferRadius.value,
          radiusUnit: 'meters',
          spatialReference: selectedStation.geometry.spatialReference
        });
        console.log('使用Circle创建缓冲区');
      } else {
        // 对于非点几何对象，创建一个备用的多边形
        console.log('非点几何对象，使用备用多边形');
        // 创建一个简单的多边形作为备用
        bufferGeometry = new Polygon({
          rings: [
            [
              [116.39, 39.9],
              [116.4, 39.9],
              [116.4, 39.91],
              [116.39, 39.91],
              [116.39, 39.9],
            ],
          ],
          spatialReference: { wkid: 4326 },
        });
      }

      // 如果返回的是数组，取第一个元素
      if (Array.isArray(bufferGeometry)) {
        bufferGeometry = bufferGeometry[0]
      }

      // 验证缓冲区几何对象
      if (!bufferGeometry || !bufferGeometry.type) {
        throw new Error('创建的缓冲区几何对象无效')
      }

      console.log('成功创建缓冲区:', bufferGeometry.type)
    } catch (error) {
      console.error('创建缓冲区出错:', error)
      // 创建一个简单的多边形作为备用
      bufferGeometry = new Polygon({
        rings: [
          [
            [116.39, 39.9],
            [116.4, 39.9],
            [116.4, 39.91],
            [116.39, 39.91],
            [116.39, 39.9],
          ],
        ],
        spatialReference: { wkid: 4326 },
      })
      console.log('使用备用缓冲区几何对象')
    }

    // 添加缓冲区图形到图层
    const bufferSymbol = new SimpleFillSymbol({
      color: [255, 140, 0, 0.2], // 橙色半透明填充
      outline: new SimpleLineSymbol({
        color: [255, 69, 0, 0.8], // 红橙色轮廓
        width: 3,
        style: 'dash', // 虚线样式
      }),
    })

    const bufferGraphic = new Graphic({
      geometry: bufferGeometry,
      symbol: bufferSymbol,
    })

    bufferGraphicsLayer?.add(bufferGraphic)

    // 查询缓冲区内的设施
    // 清空结果
    restaurantResultsRaw = []
    communityResultsRaw = []
    restaurantResults.value = []
    communityResults.value = []
    restaurantResultsCount.value = 0
    communityResultsCount.value = 0

    // 如果选择了餐饮设施，查询餐饮图层
    if (selectedFacilityTypes.value.includes('restaurant') && restaurantLayer) {
      try {
        const restaurantQuery = new Query({
          geometry: bufferGeometry,
          outFields: ['*'],
          returnGeometry: true,
          spatialRelationship: 'intersects',
        })

        // 使用try-catch包装查询操作
        const result = await restaurantLayer.queryFeatures(restaurantQuery)

        // 验证结果
        if (result && result.features) {
          // 存储原始ArcGIS对象
          restaurantResultsRaw = result.features
          console.log('餐饮查询结果', result.features)
          // 提取需要的属性到简单对象中
          restaurantResults.value = result.features.map((feature, index) => ({
            id: index,
            attributes: feature.attributes,
            // 存储ObjectID而不是几何对象
            objectId: feature.attributes.OBJECTID || feature.attributes.objectid || index,
            // 添加类型标识
            type: 'restaurant'
          }))
          restaurantResultsCount.value = restaurantResultsRaw.length
          console.log('餐饮查询结果数量:', restaurantResultsRaw.length)
        } else {
          restaurantResultsRaw = []
          restaurantResults.value = []
          restaurantResultsCount.value = 0
          console.log('餐饮查询无结果')
        }
      } catch (error) {
        console.error('餐饮设施查询出错:', error)
        restaurantResultsRaw = []
        restaurantResults.value = []
        restaurantResultsCount.value = 0
      }
    }

    // 如果选择了小区，查询小区图层
    if (selectedFacilityTypes.value.includes('community') && communityLayer) {
      try {
        const communityQuery = new Query({
          geometry: bufferGeometry,
          outFields: ['*'],
          returnGeometry: true,
          spatialRelationship: 'intersects',
        })

        // 使用try-catch包装查询操作
        const result = await communityLayer.queryFeatures(communityQuery)

        // 验证结果
        if (result && result.features) {
          // 存储原始ArcGIS对象
          communityResultsRaw = result.features
          // 提取需要的属性到简单对象中
          communityResults.value = result.features.map((feature, index) => ({
            id: index,
            attributes: feature.attributes,
            // 存储ObjectID而不是几何对象
            objectId: feature.attributes.OBJECTID || feature.attributes.objectid || index,
            // 添加类型标识
            type: 'community'
          }))
          communityResultsCount.value = communityResultsRaw.length
          console.log('小区查询结果数量:', communityResultsRaw.length)
        } else {
          communityResultsRaw = []
          communityResults.value = []
          communityResultsCount.value = 0
          console.log('小区查询无结果')
        }
      } catch (error) {
        console.error('小区查询出错:', error)
        communityResultsRaw = []
        communityResults.value = []
        communityResultsCount.value = 0
      }
    }

    // 更新设施分布图表
    nextTick(() => {
      // 如果图表实例不存在，先初始化
      if (!facilityDistributionChart && facilityDistributionChartRef.value) {
        initFacilityDistributionChart()
      }
      // 更新图表数据
      updateFacilityDistributionChart()
      // 强制重绘图表
      setTimeout(() => {
        facilityDistributionChart?.resize()
      }, 300)
    })

    // 显示结果对话框
    analysisResultVisible.value = true

    // 设置默认激活的结果标签页
    if (restaurantResultsCount.value > 0) {
      activeResultTab.value = 'restaurant'
    } else if (communityResultsCount.value > 0) {
      activeResultTab.value = 'community'
    } else {
      activeResultTab.value = 'statistics'
    }

    // 显示结果消息
    const totalResults = restaurantResultsCount.value + communityResultsCount.value
    if (totalResults > 0) {
      ElMessage.success(`在${bufferRadius.value}米范围内找到${totalResults}个设施`)
    } else {
      ElMessage.info(`在${bufferRadius.value}米范围内未找到任何设施`)
    }
  } catch (error) {
    console.error('缓冲区分析出错:', error)
    ElMessage.error('缓冲区分析失败')
  }
}

// 定位到要素
const zoomToFeature = (feature: {id: number, attributes: any, objectId: number, type: string}) => {
  if (!view) {
    console.error('地图视图未初始化')
    return
  }

  try {
    // 根据类型和id找到原始的ArcGIS对象
    let originalFeature = null;

    // 根据类型选择正确的数据源
    if (feature.type === 'restaurant' && feature.id !== undefined && feature.id < restaurantResultsRaw.length) {
      originalFeature = restaurantResultsRaw[feature.id];
    } else if (feature.type === 'community' && feature.id !== undefined && feature.id < communityResultsRaw.length) {
      originalFeature = communityResultsRaw[feature.id];
    } else if (feature.type === 'station' && feature.id !== undefined && feature.id < searchResultsRaw.length) {
      originalFeature = searchResultsRaw[feature.id];
    }

    if (!originalFeature || !originalFeature.geometry) {
      console.error('找不到对应的原始要素或几何对象为空')
      return
    }

    // 高亮显示选中的要素
    if (highlightGraphicsLayer) {
      highlightGraphicsLayer.removeAll()

      // 根据几何类型选择合适的符号
      let highlightSymbol

      if (originalFeature.geometry.type === 'point') {
        // 点要素使用SimpleMarkerSymbol
        highlightSymbol = new SimpleMarkerSymbol({
          color: [0, 255, 0, 0.8], // 绿色
          size: 12,
          outline: {
            color: [0, 128, 0, 1], // 深绿色边框
            width: 2
          }
        })
      } else {
        // 面要素使用SimpleFillSymbol
        highlightSymbol = new SimpleFillSymbol({
          color: [0, 255, 0, 0.4], // 绿色半透明填充
          outline: new SimpleLineSymbol({
            color: [0, 128, 0, 1], // 深绿色轮廓
            width: 3,
            style: 'solid', // 实线样式
          }),
        })
      }

      // 创建高亮图形
      const highlightGraphic = new Graphic({
        geometry: originalFeature.geometry.clone(), // 使用克隆的几何对象
        symbol: highlightSymbol,
      })

      highlightGraphicsLayer.add(highlightGraphic)
    }

    // 定位到要素
    console.log('正在定位到要素:', originalFeature.geometry.type)
    view.goTo({
      target: originalFeature.geometry,
      zoom: 17,
    }).catch(error => {
      console.error('定位到要素失败:', error)
    })
  } catch (error) {
    console.error('高亮显示要素出错:', error)
  }
}

// 初始化地图和图表
onMounted(() => {
  // 初始化图表
  nextTick(() => {
    // 确保图表容器已渲染
    if (facilityDistributionChartRef.value) {
      // 延迟初始化图表，确保DOM已完全渲染
      setTimeout(() => {
        initFacilityDistributionChart()
        // 初始化后立即更新数据
        updateFacilityDistributionChart()
      }, 300)
    }

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  })

  // 创建地铁线路图层
  subwayLineLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/1',
    title: '地铁线路',
    visible: layerVisibility.value.subwayLine,
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建地铁站点图层
  subwayStationLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/地铁站点/FeatureServer/0',
    title: '地铁站点',
    visible: layerVisibility.value.subwayStation,
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple',
      symbol: new PictureMarkerSymbol({
        url: subway,
        width: 24,
        height: 24,
      }),
    },
  })

  // 创建餐饮设施图层
  restaurantLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/济南餐饮数据/FeatureServer/0',
    title: '餐饮设施',
    visible: layerVisibility.value.restaurant,
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建小区图层
  communityLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/WAsbhBMtbJ0DBeIA/arcgis/rest/services/小区/FeatureServer/0',
    title: '小区',
    visible: layerVisibility.value.community,
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建缓冲区图形图层
  bufferGraphicsLayer = new GraphicsLayer({
    title: '缓冲区',
  })

  // 创建高亮图形图层
  highlightGraphicsLayer = new GraphicsLayer({
    title: '高亮',
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [
      subwayLineLayer,
      subwayStationLayer,
      restaurantLayer,
      communityLayer,
      bufferGraphicsLayer,
      highlightGraphicsLayer,
    ],
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.397428, 39.90923], // 默认中心点（北京）
  })

  // 监听点击事件，用于查询要素信息
  view.on('click', async function (event) {
    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 0.5 // 增加点击容差
    query.units = 'kilometers'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询地铁站点图层
      if (subwayStationLayer && subwayStationLayer.visible) {
        const stationResult = await subwayStationLayer.queryFeatures(query)
        if (stationResult.features.length > 0) {
          // 找到站点，显示信息
          selectedStation = stationResult.features[0]
          hasSelectedStation.value = true
          stationInfoVisible.value = true

          nextTick(() => {
            stationRefreshKey.value++
          })
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })
})

// 初始化设施分布图表
const initFacilityDistributionChart = () => {
  if (facilityDistributionChartRef.value) {
    // 如果已经存在图表实例，先销毁
    if (facilityDistributionChart) {
      facilityDistributionChart.dispose()
    }

    // 确保容器有正确的尺寸
    const container = facilityDistributionChartRef.value
    if (container.clientWidth === 0 || container.clientHeight === 0) {
      container.style.width = '100%'
      container.style.height = '300px'
    }

    // 创建新的图表实例
    facilityDistributionChart = echarts.init(container)

    // 检查是否有数据
    const hasData = (restaurantResultsCount.value > 0 || communityResultsCount.value > 0)

    // 设置图表选项
    facilityDistributionChart.setOption({
      backgroundColor: '#fff',
      title: {
        text: hasData ? '设施类型占比' : '设施类型占比 (暂无数据)',
        left: 'center',
        top: 0,
        textStyle: {
          fontSize: 16,
          color: hasData ? '#333' : '#999'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'horizontal',
        bottom: 10,
        data: ['餐饮设施', '小区'],
        show: hasData
      },
      series: [
        {
          name: '设施类型分布',
          type: 'pie',
          radius: ['40%', '60%'],
          center: ['50%', '50%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: hasData,
            formatter: '{b}: {c} ({d}%)'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: hasData
          },
          data: hasData ? [
            {
              value: restaurantResultsCount.value || 0,
              name: '餐饮设施',
              itemStyle: { color: '#ff9800' }
            },
            {
              value: communityResultsCount.value || 0,
              name: '小区',
              itemStyle: { color: '#4caf50' }
            }
          ] : [
            {
              value: 1,
              name: '暂无数据',
              itemStyle: { color: '#e0e0e0' }
            }
          ]
        }
      ]
    })

    // 绑定窗口大小变化事件
    window.addEventListener('resize', () => {
      facilityDistributionChart?.resize()
    })
  }
}

// 更新设施分布图表数据
const updateFacilityDistributionChart = () => {
  if (facilityDistributionChart) {
    // 确保数据有效（非零值）
    const restaurantCount = restaurantResultsCount.value || 0
    const communityCount = communityResultsCount.value || 0

    // 如果两个值都为0，添加一个提示
    if (restaurantCount === 0 && communityCount === 0) {
      facilityDistributionChart.setOption({
        title: {
          text: '设施类型占比 (暂无数据)',
          left: 'center',
          top: 0,
          textStyle: {
            fontSize: 16,
            color: '#999'
          }
        },
        series: [
          {
            data: [
              {
                value: 1,
                name: '暂无数据',
                itemStyle: { color: '#e0e0e0' }
              }
            ]
          }
        ]
      })
    } else {
      // 正常更新数据
      facilityDistributionChart.setOption({
        title: {
          text: '设施类型占比',
          textStyle: {
            color: '#333'
          }
        },
        series: [
          {
            data: [
              {
                value: restaurantCount,
                name: '餐饮设施',
                itemStyle: { color: '#ff9800' }
              },
              {
                value: communityCount,
                name: '小区',
                itemStyle: { color: '#4caf50' }
              }
            ]
          }
        ]
      })
    }

    // 强制重绘
    facilityDistributionChart.resize()
  } else if (facilityDistributionChartRef.value) {
    // 如果图表不存在但容器存在，初始化图表
    initFacilityDistributionChart()
  }
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  facilityDistributionChart?.resize()
}

// 监听分析结果对话框的显示状态
watch(analysisResultVisible, (newVal) => {
  if (newVal && activeResultTab.value === 'statistics') {
    // 当对话框显示且当前标签是统计信息时，确保图表正确渲染
    nextTick(() => {
      // 如果图表实例不存在，先初始化
      if (!facilityDistributionChart && facilityDistributionChartRef.value) {
        initFacilityDistributionChart()
        updateFacilityDistributionChart()
      }

      // 延迟一点时间确保DOM已完全渲染
      setTimeout(() => {
        facilityDistributionChart?.resize()
      }, 300)
    })
  }
})

// 监听结果标签页的变化
watch(activeResultTab, (newVal) => {
  if (newVal === 'statistics' && analysisResultVisible.value) {
    // 当切换到统计信息标签时，确保图表正确渲染
    nextTick(() => {
      // 如果图表实例不存在，先初始化
      if (!facilityDistributionChart && facilityDistributionChartRef.value) {
        initFacilityDistributionChart()
        updateFacilityDistributionChart()
      }

      // 延迟一点时间确保DOM已完全渲染
      setTimeout(() => {
        facilityDistributionChart?.resize()
      }, 300)
    })
  }
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view.destroy()
    view = null
  }

  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)

  // 销毁图表实例
  facilityDistributionChart?.dispose()
})
</script>

<style lang="scss" scoped>
.page-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.metro-title {
  margin: 0 0 16px 0;
  font-size: 24px;
  color: #409eff;
  display: flex;
  align-items: center;

  .metro-icon {
    display: inline-block;
    width: 24px;
    height: 24px;
    margin-right: 8px;
    background-color: #409eff;
    border-radius: 50%;
  }
}

.map-view {
  flex: 1;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.layer-control-panel {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 10;
  width: 320px;
}

.layer-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.metro-checkbox {
  margin-right: 0;
}

.metro-input {
  width: 100%;
}

.buffer-analysis-tip {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.search-radius-slider {
  margin: 16px 0;
}

.facility-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin: 16px 0;
}

.buffer-analysis-btn {
  width: 100%;
  margin-top: 8px;
}

.station-info {
  p {
    margin: 8px 0;
  }
}

.statistics-info {
  padding: 16px 0;

  .chart-container {
    height: 300px !important;
    width: 100% !important;
    margin-top: 16px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
    background-color: #fff;
  }
}
</style>
